package com.redispro.interceptors;

import cn.hutool.core.bean.BeanUtil;
import com.redispro.dto.UserDTO;
import com.redispro.utils.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.*;
import java.time.Duration;
import java.util.Map;

/**
 * @Auther: 李 力
 * @Date: 2024/11/23
 * @Description: com.redispro.interceptors
 * @version: 1.0
 */
public class ReFreshInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public ReFreshInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("authorization");
        //2.从redis中取出用户
        Map<Object, Object> map = redisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        if (!map.isEmpty()) {
            UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
            //3.存入threadLocal
            UserHolder.saveUser(userDTO);
            //4.刷新token有效期
            redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, Duration.ofMinutes(30));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
